local stats = ngx.shared.stats
local now = ngx.now()
local timestamp = math.floor(now)
local minute_key = os.date("%Y-%m-%d %H:%M", timestamp)

-- 获取当前分钟的 key
local current_key = stats:get("current_minute_key")

-- 如果分钟变了，保存上一分钟的数据到日志
if current_key and current_key ~= "" and current_key ~= minute_key then
    local count = stats:get("current_minute_count") or 0
    if count > 0 then
        local log_file = io.open("/usr/local/openresty/nginx/logs/stats.log", "a")
        if log_file then
            log_file:write(string.format("%s|%d\n", current_key, count))
            log_file:flush()
            log_file:close()
            ngx.log(ngx.INFO, "Saved stats: ", current_key, " count: ", count)
        else
            ngx.log(ngx.ERR, "Failed to open stats.log")
        end
    end
    -- 重置计数
    stats:set("current_minute_count", 0)
end

-- 更新当前分钟
stats:set("current_minute_key", minute_key)
stats:incr("current_minute_count", 1, 0)
